/**
 * Copyright (c) 2020 Raspberry Pi (Trading) Ltd.
 *
 * SPDX-License-Identifier: BSD-3-Clause
 */

// Example of reading/writing an external serial flash using the PL022 SPI interface

#include <stdio.h>
#include "pico/stdlib.h"
#include "pico/binary_info.h"
#include "hardware/spi.h"

#include "wizchip_conf.h"
#include "w5100s.h"
#include "w5100s_spi.h"
#include "dns.h"

#define ETHERNET_BUF_MAX_SIZE (1024 * 2)

void network_init(void);
int dns_test(void);
bool repeating_timer_callback(struct repeating_timer *t);

wiz_NetInfo net_info = {
    .mac = {0x00, 0x08, 0xdc, 0x16, 0xed, 0x2e},
    .ip = {192, 168, 1, 10},
    .sn = {255, 255, 255, 0},
    .gw = {192, 168, 1, 1},
    .dns = {8, 8, 8, 8},
    .dhcp = NETINFO_STATIC};
wiz_NetInfo get_info;
static uint8_t ethernet_buf[ETHERNET_BUF_MAX_SIZE] = {0,};
uint8_t DNS_2nd[4] = {114,114,114,114};
uint8_t Domain_name[] = "www.baidu.com";
uint8_t Domain_IP[4] = {0,};


int main()
{   
    struct repeating_timer timer;
    stdio_init_all();
    sleep_ms(2000);
    network_init();
    DNS_init(0,ethernet_buf);
    add_repeating_timer_ms(1000, repeating_timer_callback, NULL, &timer);
    while (true)
    {
        if(dns_test())
            while(true);
        sleep_ms(2000);
    }   
}

void network_init(void)
{
    uint8_t temp;
    wizchip_initialize();
    printf("W5100s dns test example.\r\n");
    sleep_ms(2000);
    wizchip_setnetinfo(&net_info);
    print_network_information(get_info);
    sleep_ms(2000);   
}

int dns_test(void)
{
    int ret;
    printf("\r\n===== DNS Client Example =====\r\n");
    printf("> DNS 1st: %d.%d.%d.%d\r\n",net_info.dns[0],net_info.dns[1],net_info.dns[2],net_info.dns[3]);
    printf("> DNS 2nd: %d.%d.%d.%d\r\n",DNS_2nd[0],DNS_2nd[1],DNS_2nd[2],DNS_2nd[3]);
    printf("==============================\r\n");
    printf("> Example Domain Name : %s\r\n",Domain_name);

    if((ret = DNS_run(net_info.dns, Domain_name, Domain_IP)) > 0)
    {
        printf("> 1st DNS Reponsed\r\n");
    }
    else if((ret != -1) && ((ret = DNS_run(DNS_2nd, Domain_name, Domain_IP)) > 0))
    {
        printf("> 2nd DNS Responsed\r\n");
    }
    else if(ret == -1)
    {
        printf("> MAX_DOMAIN_NAME is too small. Should be redefined it. \r\n");
    }
    else
    {
        printf("> DNS Failed\r\n");
    }
    if(ret > 0)
    {
        printf("> Translated %s to %d.%d.%d.%d\r\n",Domain_name,Domain_IP[0],Domain_IP[1],Domain_IP[2],Domain_IP[3]);
        return 1;
    }
    return 0;
}

/* Timer */
bool repeating_timer_callback(struct repeating_timer *t)
{
    DNS_time_handler();
    return true;
}
